package com.zhkj.txg.module.mine.ui

import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.txg.R
import com.zhkj.txg.module.login.ui.BindMobileActivity
import com.zhkj.txg.module.mine.vm.MineViewModel
import com.zhkj.txg.utils.ThirdLoginUtils
import kotlinx.android.synthetic.main.activity_account_safe.*

class AccountSafeActivity : ViewModelActivity<MineViewModel>() {
    override fun setViewModel(): MineViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleSetting
    override val layoutResId: Int = R.layout.activity_account_safe

    private val requestCodeBindMobile = 1029

    override fun initUI() {
        // 绑定微信
        viewSettingWx.setOnClickListener {
            ThirdLoginUtils.wxLogin(this)
        }
        // 绑定手机
//        viewSettingMobile.setOnClickListener {
//            BindMobileActivity.changeMobile(this, requestCodeBindMobile)
//        }
    }

    override fun initViewModel() {
        // 微信授权信息观察者
        viewModel.weChatBindSubscribe().observe(this, Observer {
            if (it.success) viewModel.bindWeChat(it.code)
        })
        // 绑定微信结果观察者
        viewModel.bindWeChatLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                toast(getString(R.string.bind_success))
                initData()
            }
        })
        // 绑定数据观察者
        viewModel.userBindLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                viewSettingWx.isEnabled = !it.bindWeChat
                tvSettingBind.text = getString(if (it.bindWeChat) R.string.bind else R.string.not_bind)
                tvSettingMobile.text = it.mobile
            }
        })
    }

    override fun initData() {
        viewModel.userBind()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == requestCodeBindMobile) {
            viewModel.userBind()
        }
    }
}